package com.jt.auth.config;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
/*        //super.configure(http);
        //禁用跨域攻击，假如没有禁用，使用postman，httpclient这些工具登录失败403
        http.csrf().disable();
        //所有**资源必须认证才能访问，403没有权限
        http.authorizeRequests().antMatchers("/**").authenticated();
        //放行所有的资源(在资源服务中授权)
        http.authorizeRequests().anyRequest().permitAll();
        //配置需要认证的，例如default.html，其它的都放行
        http.authorizeRequests().antMatchers("default.html")
                .authenticated().anyRequest().permitAll();
        //登录配置,去哪里认证，认证成功或失败的处理器是谁
        http.formLogin().defaultSuccessUrl("index.html");*/

        //前后端分离的写法，登录成功要返回json字符串
        http.formLogin()
                .successHandler(successHandler())
                .failureHandler(failureHandler());
    }
    @Bean
    public AuthenticationSuccessHandler successHandler() {
        return(request,response,authentication) ->{
            Map<String,Object> map = new HashMap<>();
            map.put("status", 200);
            map.put("message", "login success");
            writeJsonToClient(response,map);
        };
    }
    public AuthenticationFailureHandler failureHandler() {
        return (request , response ,authentication) ->{
            Map<String, Object> map = new HashMap<>();
            map.put("status", 201);
            map.put("message", "login failure");
            writeJsonToClient(response,map);
        };
    }
    private void writeJsonToClient(HttpServletResponse response, Map<String, Object> map) throws IOException {
        String jsonStr = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset:utf8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.println(jsonStr);
        out.flush();
    }

}
